﻿using Prism.Common;
using Prism.Events;
using Prism.Regions;
using System.Collections;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using TransformerManager.Shared.Dto.Conservator;
using TransformerManager.WPF.Common.Helper.Events;
using TransformerManager.WPF.Common.ViewModels;

namespace TransformerManager.WPF.Common.Views
{
    /// <summary>
    /// Interaction logic for ConservatorInfoTemplate
    /// </summary>
    public partial class ConservatorInfoTemplate : UserControl
    {
        private readonly IEventAggregator _eventAggregator;

        public ConservatorInfoTemplate(IEventAggregator eventAggregator)
        {
            InitializeComponent();

            _eventAggregator = eventAggregator;

            RegionContext.GetObservableContext(this).PropertyChanged += ConservatorInfo_PropertyChanged;

            _eventAggregator.GetEvent<ReloadXmlDataPageEvent>()
                .Subscribe(ReloadXmlData, ThreadOption.PublisherThread, false,
                msg => msg.Contains(nameof(ConservatorInfoTemplate)));
        }
        private void ConservatorInfo_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // sender是名为DetailInfoRegion的控件ContentControl下绑定的BasicInfosDto参数
            var context = (ObservableObject<object>)sender;
            var convDto = (ConservatorDto)context.Value;
            // 赋值给BasicInfosTemplateViewModel 下定义的BasicInfosDto方法
            (DataContext as ConservatorInfoTemplateViewModel).ConservatorDto = convDto;
        }

        private async void ReloadXmlData(string value)
        {
            foreach (DictionaryEntry resource in Resources)
            {
                string typeName = resource.Value.GetType().Name;
                if (typeName == "XmlDataProvider")
                {
                    await Task.Factory.StartNew(() =>
                    {
                        ((XmlDataProvider)resource.Value).Refresh();
                    });

                }
            }
        }

    }
}
